<?php

namespace Frontend\Controllers;

use Phalcon\Mvc\Controller;
use Phalcon\Mvc\Dispatcher;
use Models\Topics;
use Models\Doctypes;
use Forms\SearchForm;

class ControllerBase extends Controller {

    public function initialize() {
        $doctypes = Doctypes::find()->toArray();
        foreach ($doctypes as $key => $type) {
            $doctypes[$key]['topics'] = Topics::find("doctype_id = '" . $type['id'] . "'")->toArray();
        }
        $this->view->title = 'VIDS';
        $this->view->menu = $doctypes;
        $this->view->text_search = '';
        $this->view->page = 1;
        $this->view->limit = 10;
        $this->view->orderby = '';
        if ($this->dispatcher->getActionName() == 'index' && $this->dispatcher->getControllerName() == 'index') {
            $this->view->loginparam = 'login';
        } else {
            $this->view->loginparam = 'login?url=' . preg_replace('/(\/+)/','/',$this->url->get($this->router->getRewriteUri()));
        }
    }

    public function beforeExecuteRoute(Dispatcher $dispatcher) {
        $controllerName = $dispatcher->getControllerName();

        $identity = $this->auth->getIdentity();
        if ($this->acl->isPrivate($dispatcher->getModuleName(), $controllerName)) {
            $actionName = $this->getActionName($dispatcher->getActionName());

            if (!$this->acl->isAllowed($identity['profile'], $dispatcher->getModuleName() . $controllerName, $actionName)) {

                $this->flash->error('You don\'t have access to this module: ' . $controllerName . ':' . $actionName);

                if ($this->acl->isAllowed($identity['profile'], $controllerName, 'index')) {
                    $dispatcher->forward(array(
                        'module' => 'frontend',
                        'controller' => $controllerName,
                        'action' => 'index'
                    ));
                } else {
                    $dispatcher->forward(array(
                        'module' => 'frontend',
                        'controller' => 'error',
                        'action' => 'index'
                    ));
                }
                return false;
            }
        }
        $this->view->auth = $identity;
    }

}
